<!--
 * @Author: yanzengyong 709402944@qq.com
 * @Date: 2025-08-25 09:54:19
 * @LastEditors: yanzengyong 709402944@qq.com
 * @LastEditTime: 2025-08-26 00:11:16
 * @FilePath: /cyj-framwk-web/src/components/Form/src/cyj/components/UserSelectNative.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<template>
  <okEmployeeSelect
    :value="value"
    :multiple="multiple"
    ref="vokSelect"
    :getContainerModal="getContainer"
    :queryUserExtendBackFields="queryUserExtendBackFields"
    :propsGetInfoByEmpId="onPropsGetInfoByEmpId"
    :queryDeptUser="onQueryDeptUser"
    :getInfoById="onGetInfoById"
    :remoteMethod="onQueryDeptUser"
    :getRootDept="onGetRootDept"
    :getSubDept="onGetSubDept"
    :update="handleSelectChange"
    :hideSelect="true"
    :customOpenModal="false"
    v-bind="$attrs"
    :theme="appTheme"
  />
</template>
<script lang="ts" setup>
  import { ref, watch, watchEffect } from 'vue';
  import { okEmployeeSelect } from '@byteluck/ok-wc-ui';
  import { queryDepartTreeSync, getUserList } from '/@/api/common/api';
  import { cloneDeep } from 'lodash-es';
  import { inject } from 'vue';

  const emit = defineEmits(['change']);
  const props = defineProps({
    value: String,
    placeholder: String,
    disabled: Boolean,
    multiple: {
      type: Boolean,
      default: false,
    },
    labelKey: {
      type: String,
      default: 'realname',
    },
    rowKey: {
      type: String,
      default: 'id',
    },
    params: {
      type: Object,
      default: () => {},
    },
    //排除用户id的集合
    excludeUserIdList: {
      type: Array,
      default: () => [],
    },
  });
  const getContainer = () => document.body;
  /**百特搭弹窗方法 */

  const vokSelect = ref();
  const openModalClick = () => {
    console.log('vokSelect.value--------', vokSelect.value);
    vokSelect.value.openTreeStructure();
  };

  const appTheme = inject('appTheme');
  const queryUserExtendBackFields = ['orgCode'];

  const onLoadData = async (params?: any) => {
    const queryParams = { primaryKey: 'key', ...params };
    const list = await queryDepartTreeSync(queryParams);
    return list;
  };

  const onPropsGetInfoByEmpId = async (id: string) => {
    const rowKey = props.rowKey;
    const filterParams: any = {};
    filterParams[rowKey] = id;
    const res = await getUserList(filterParams);
    const result = convertUserListForResult(res?.records || []);
    return {
      code: '000000',
      data: result.data?.[0] || {},
    };
  };

  const onGetInfoById = async (ids: string[] | string) => {
    let queryIds = '';
    if (typeof ids === 'object') {
      queryIds = ids.join(',');
    } else {
      queryIds = ids;
    }

    const rowKey = props.rowKey;
    const filterParams: any = {};
    filterParams[rowKey] = queryIds;
    const res = await getUserList(filterParams);
    const result = convertUserListForResult(res?.records || []);
    return result;
  };

  const onQueryDeptUser = async (params: { value: string; ids: string; org_ids: string; page: any; orgCode: string }) => {
    const filterParams: any = {
      pageNo: params.page.page_index,
      pageSize: params.page.page_size,
    };
    const orgCode = params.orgCode;
    if (orgCode) {
      filterParams.orgCode = orgCode;
    }
    const value = params.value;
    const rowKey = props.rowKey;
    const labelKey = props.labelKey;
    if (value) {
      filterParams[rowKey] = `*${value}*`;
      filterParams[labelKey] = `*${value}*`;
      filterParams['username'] = `*${value}*`;
    }
    const res = await getUserList(filterParams);
    const result = convertUserListForResult(res?.records || []);
    return result;
  };

  const onGetRootDept = async () => {
    const list = await onLoadData();
    const newList = list.map((item: any) => {
      return {
        org_id: item.id,
        org_name: item.departName,
        org_type: 'INTERNAL',
        org_tag_code: null,
        org_tag_name: null,
        dept_name_path: item.departName,
        has_child: item.isLeaf,
        orgCode: item.orgCode,
      };
    });
    return {
      code: '000000',
      data: newList,
    };
  };

  const convertUserListForResult = (list: any[]) => {
    const rowKey = props.rowKey;
    const labelKey = props.labelKey;
    const newList = list.map((item: any) => {
      const employeeName = item[labelKey];
      const employeeId = item[rowKey];
      return {
        employee_name: employeeName,
        employee_id: employeeId,
        email: item.email,
        avatar_url: item.avatar,
        department_id: item.orgCode,
        dept_id_path: null,
        dept_name_path: null,
        department_name: item.orgCodeTxt,
        phone: item.phone,
        org_type: 'INTERNAL',
        cur_dept: {
          dept_id: item.orgCode,
          dept_name: item.orgCodeTxt,
          dept_id_path: null,
          dept_name_path: item.orgCodeTxt,
        },
      };
    });
    return {
      code: '000000',
      data: newList,
    };
  };

  const convertDepartmentListForResult = (list: any[]) => {
    const newList = list.map((item: any) => {
      return {
        department_name: item.departName,
        department_id: item.id,
        parent_id: item.parentId,
        dept_level_no: null,
        dept_id_path: item.id,
        dept_name_path: item.departName,
        display_value: item.departName,
        order: null,
        has_child: false,
        org_type: null,
        label_name: null,
        org_id: item.orgCode,
        has_child: !item.isLeaf,
        orgCode: item.orgCode,
      };
    });
    return {
      code: '000000',
      data: newList,
    };
  };

  const onGetSubDept = async (parentDepartmentId: string, displayLevel: number, page: { page_index: number; page_size: number }) => {
    const params: any = { pid: parentDepartmentId };
    const list = await onLoadData(params);
    const result = convertDepartmentListForResult(list);
    return result;
  };

  const send = (values) => {
    let result = typeof props.value == 'string' ? values.join(',') : values;
    emit('update:value', result);
    emit('change', result);
    // if (!values || values.length == 0) {
    //   emit('select', null, null);
    // }
  };

  const handleSelectChange = (values, options) => {
    // const value = cloneDeep(values);
    // send(value);
    emit('change', values, options);
  };

  defineExpose({
    openModalClick,
  });
  /**百特搭弹窗方法 */
</script>
